﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BoYuanCore.CoreCodeTemplates.FineUICore;


namespace BoYuanCore.CoreCodeTemplates.FineUICore.Template
{
    public class ControllerTemplate : FineUIBase
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tb"></param>
        /// <param name="haveListPage"></param>
        /// <param name="haveAddPage"></param>
        /// <param name="haveViewPage"></param>
        /// <param name="haveEGPage"></param>
        /// <param name="haveOPPage"></param>
        /// <returns></returns>
        public static string GetCode(TableModel tb, bool haveListPage = true, bool haveAddPage = true, bool haveViewPage = false, bool haveEGPage = false, bool haveOPPage = false)
        {
            List<DbColumnInfo> list = tb.Columns;
            DbColumnInfo keyModel = list.FirstOrDefault(p => p.IsPrimaryKey == true);
            if (keyModel == null) { throw new Exception("表没有主键，没办法生成代码！ControllerTemplate"); }
            List<DbColumnInfo> list2 = list.Where(p => p.IsPrimaryKey == false).ToList();//非主键列

            StringBuilder pageCode = new StringBuilder();

            if (haveListPage)
            {
                pageCode.Append(GetListPageCode(tb));
            }

            if (haveAddPage)
            {
                pageCode.Append(GetAddPageCode(tb, keyModel, list2));
            }

            return GetControllerCode(tb, pageCode.ToString());
        }

        /// <summary>
        /// addpage 相关代码
        /// </summary>
        /// <param name="tb"></param>
        /// <param name="keyModel">主键列信息</param>
        /// <param name="list2">非主键列集合</param>
        /// <returns></returns>
        private static string GetAddPageCode(TableModel tb, DbColumnInfo keyModel, List<DbColumnInfo> list2)
        {
            GetControlMappingCode(list2, out string modelValue, out string updateColumn, out string insertColumn);

            string updateColumns = "p => new {" + updateColumn.Substring(1) + "}";

            string code = string.Format(@"
       
        #region AddPage

        public ActionResult Add()
        {{
            if (long.TryParse(Request.Query[""id""], out long id))//编辑页面初始化
            {{
                {2}.{0} mo = FreeSqlHelper.GetModel<{2}.{0}>(id);
                ViewBag.haveUpdate = 1;//判断是否为编辑状态

                return View(mo);
            }}
            return View();//添加页面
        }}

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult BtnSave_OnClick(IFormCollection fc)
        {{
            bool isEdit = long.TryParse(fc[""f_ID""], out long {1});

            {2}.{0} mo = new {2}.{0}();
{3}

            if (!isEdit)//添加
            {{
{5}
                if (FreeSqlHelper.InsertModel(mo) > 0)
                {{
                    AlertInfor(""添加成功"", true);
                }}
                else
                {{
                    NotifyError(""添加失败"");
                }}
            }}
            else//修改
            {{
                mo.ID = {1};
                int returnNum = FreeSqlHelper.UpdateModels(mo,
//注意更新字段是否对应，数量是否一致 
{4}
                                );
                if (returnNum > 0)
                {{
                    AlertInfor(""修改成功"", true);
                }}
                else
                {{
                    NotifyError(""修改失败"");
                }}
            }}
            return UIHelper.Result();
        }}
        #endregion

"

                , tb.TableNameToClassName               //0
                , (!keyModel.IsIdentity && keyModel.PropertyName == "long") ? "ID" : keyModel.DbColumnNameToClassName      //1 非自增long类型主键为雪花ID
                , tb.ModelName               //2
                , modelValue                 //3
                , updateColumns              //4
                , insertColumn               //5

            );
            return code;
        }


        private static string GetListPageCode(TableModel tb)
        {
            string code = string.Format(@"

        #region ListPage
        // GET: {0}/{1}
        public ActionResult ListPage()
        {{
            return View();
        }}

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ShowGrid(IFormCollection fc)
        {{
            var keyword=fc[""txb_keyword""].ToString().Trim();
            var query = DB.Select<{2}.{1}>()
                //todo 筛选
                //.WhereIf(keyword.Length > 0, p=> )
                .OrderBy(p => p.ID);

            var grid1 = UIHelper.Grid(""Grid1"");
            grid1.BindGrid(fc, ""ddlPageSize"", query);
            return UIHelper.Result();
        }}

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult BtnDelete_Click(string ids)
        {{
            if (string.IsNullOrWhiteSpace(ids))
            {{
                NotifyQuestion(""请选择要删除的选中行！"");
            }}
            else
            {{
                var idList = Array.ConvertAll<string, long>(ids.Substring(1).Split(','), long.Parse);
                if (idList.Length == 0)
                {{
                    NotifyQuestion(""请选择要删除的选中行！"");
                }}
                else
                {{
                    DB.Delete<{2}.{1}>().Where(p => idList.Contains(p.ID)).ExecuteAffrows();
                    AlertSuccess(""删除成功！"", false, ""onGridBind()"");
                }}
            }}
            return UIHelper.Result();
        }}
        #endregion

"

                , tb.Namespace2Str           //0
                , tb.TableNameToClassName               //1
                , tb.ModelName               //2

            );

            return code;
        }


        private static string GetControllerCode(TableModel tb, string addCode)
        {
            string code = string.Format(@"
using FineUICore;

using System;
using System.Linq;
using {4}.DBServices.Base;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace {0}.Areas.{1}.Controllers
{{
    [Area(""{1}"")]
    public partial class {2}Controller : {3}
    {{
        private readonly ILogger<{2}Controller> _logger;
        public {2}Controller(ILogger<{2}Controller> logger) : base(logger)
        {{
            _logger = logger;
        }}

        {5}
        
    }}
}}

"
                , tb.NamespaceStr            //0
                , tb.Namespace2Str           //1
                , tb.TableNameToClassName               //2
                , tb.ClassnameStr            //3
                , tb.NamespaceStr.Split('.')[0] //4  using BoYuanCore.DBServices.Base;
                , addCode
            );

            return code;
        }

    }
}